    //
//  CompanyDetaiVC_iPad.m
//  WRY
//
//  Created by Yang on 11/2/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "CompanyDetaiVC_iPad.h"
#import "AppDelegate_iPad.h"
#import "CommonJson.h"
#import "WebPath.h"
#import "FocusDataMethod.h"
#import "CommonView_iPad.h"
#import "BigMapVC.h"
#import "RootVC_iPad.h"
#import "NSStringExtra.h"

@implementation CompanyDetaiVC_iPad
@synthesize backgroundImageView,leftSeg,rightSeg,focusBt,
companyName,focusImageView,mapView,factorBtHolder,maskView,mapButton;


@synthesize name,code;
@synthesize marksiteCode,markfactoryCode,marksitetypeCode,markEnterpriseCode,markEnterpriseTypeCode;
@synthesize popControlller;
@synthesize activityView;
@synthesize detaiVCdelegate;


#pragma mark Preset methods
- (void)showConnectionError {
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
													message:@"Connection error" 
												   delegate:nil
										  cancelButtonTitle:@"OK" 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];
}
- (void)showLoading {
	if (loadingLabel == nil) 
	{
		float centerX ;
		float centerY;
		centerX = self.view.bounds.size.width/2;
		centerY =self.view.bounds.size.height/2; 
		CGPoint center = CGPointMake(centerX, centerY);
		loadingBackImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"but90x30.png"]];
		loadingBackImage.frame = CGRectMake(0.0f, 0.0f, 90.0f, 30.0f);
		loadingBackImage.center = center;
		[self.view addSubview:loadingBackImage];
		[loadingBackImage release];
		
		loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 90.0f, 30.0f)];
		loadingLabel.font = [UIFont boldSystemFontOfSize:12.0f];
		loadingLabel.backgroundColor = [UIColor clearColor];
		loadingLabel.text = @"加载中...";
		loadingLabel.textColor = [UIColor darkGrayColor];
		loadingLabel.center = CGPointMake(centerX+32, centerY);
		[self.view addSubview:loadingLabel];
		[loadingLabel release];
		activeIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
		activeIndicator.center = CGPointMake(centerX - 28, centerY);
		[self.view addSubview:activeIndicator];
		[activeIndicator release];
		
	}
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	//self.userInteractionEnabled = NO;
	maskButton.userInteractionEnabled = YES;
	loadingBackImage.hidden = NO;
	activeIndicator.hidden = NO;
	[activeIndicator startAnimating];
	loadingLabel.hidden = NO;
	[self.view bringSubviewToFront:loadingBackImage];
	[self.view bringSubviewToFront:activeIndicator];
	[self.view bringSubviewToFront:loadingLabel];
	
}
- (void)hideLoading {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	//self.userInteractionEnabled = YES;
	maskButton.userInteractionEnabled = NO;
	loadingBackImage.hidden = YES;
	activeIndicator.hidden = YES;
	[activeIndicator stopAnimating];
	loadingLabel.hidden = YES;
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[leftSeg setTintColor:[UIColor colorWithRed:80.0f/255.0f green:108.0f/255.0f blue:151.0f/255.0f alpha:1.0f]];
	infoDict = [[NSMutableDictionary alloc] init];//企业信息
	factorData = [[NSMutableArray alloc] init];//排放口
	dataArray = [[NSMutableArray alloc] init];//数据
	subFactors = [[NSMutableArray alloc] init];//因子
    selectDate = [NSDate date];
	selectedFactorDict = [[NSMutableDictionary alloc] init];//选中因子
	
	NSString *path = [[NSBundle mainBundle] pathForResource:@"CompanyInfoData" ofType:@"plist"];
	infoKeyArray = [[NSArray alloc] initWithContentsOfFile:path];
	
	
	
	//曲线图
	curveController = [[SC_CurveChartVC alloc] init];
	[curveController setForIpad];
	[curveController setViewFrame:CGRectMake(23.0f, 172.0f, 687.0f, 456.0f)];
	[self.view addSubview:curveController.view];
	curveController.view.backgroundColor = [UIColor clearColor];
	
	//地图delegate
	mapView.delegate = self;
	
    [super viewDidLoad];
	
	maskButton = [UIButton buttonWithType:UIButtonTypeCustom];
	maskButton.frame = self.view.bounds;
	[self.view addSubview:maskButton];
	maskButton.userInteractionEnabled = NO;

}

- (void)setForFocusDetail {
	backgroundImageView.image = [UIImage imageNamed:@"background1.png"];
	rightSeg.center = CGPointMake(873.0f,164.0f);
	//[curveController changeViewFrame:CGRectMake(23.0f, 172.0f, 687.0f, 320.0f)];
	curveController.view.frame = CGRectMake(23.0f, 172.0f, 687.0f, 320.0f);
	[[(SC_CurveChartView *)curveController.view indicatorView] resetFrame:CGRectMake(0.0f, 0.0f, 687.0f, 320.0f)];
	
	[curveController.view setNeedsDisplay];
	listTable.frame = CGRectMake(731.0f, 178.0f, 282.0f, 319.0f);
	mapView.frame = CGRectMake(740.0f, 20.0f, 267.0f, 100.0f);
	mapButton.frame = mapView.frame;
	
	focusController = [[FocusListVC_iPad alloc] init];
	focusController.delegate = self;
	[self.view addSubview:focusController.view];
	CGRect frame = focusController.view.frame;
	frame.origin.y = 512.0f;
	focusController.view.frame = frame;
	
//	[self.view addSubview:maskView];
//	maskView.hidden = NO;
	
}

- (void)reset {
	[infoDict setDictionary:[NSDictionary dictionary]];
	leftSeg.selectedSegmentIndex = 0;
	rightSeg.selectedSegmentIndex = 0;
	companyName.text = @"";
	[listTable reloadData];
}
- (void)beginRequestForCompany:(NSString *)companyCode companyTypeCode:(NSString *)companyTypeCode {
	self.markEnterpriseCode=companyCode;
    self.markEnterpriseTypeCode=companyTypeCode;
	[self reset];
	code = companyCode;
	if ([[FocusDataMethod sharedInstance] companyExisting:code]) {
		focusImageView.hidden = NO;
		[focusBt setTitle:@"取消关注" forState:UIControlStateNormal];
	}
	else {
		focusImageView.hidden = YES;
		[focusBt setTitle:@"关注企业" forState:UIControlStateNormal];
		}
	[self requestCompanyInfo];
	[self requestFactorList];
	
}
- (void)requestCompanyInfo {
	if (![infoDict allKeys].count) {
		//[self showLoading];
		NSString *body = [NSString stringWithFormat:@"LoginGuid=%@&EnterpriseCode=%@&EnterpriseType=%@",
						  [[AppDelegate_iPad currentDelegate] GUID],code,markEnterpriseTypeCode];
		
		[[CommonJson sharedInstance] requestToPath:[WebPath enterprisePath]
										methodName:@"Search__EnterpriseBaseInfo" 
										bodyString:body 
										 targetObj:self
								  targetMethodName:@"eventForCompanyInfo:" 
				  						notifiName:@"RequestCompanyInfo"];
	}
}
- (void)eventForCompanyInfo:(NSNotification *)notification {
	[[CommonJson sharedInstance] removeTarget:self notiName:[notification name]];
	[self hideLoading];
	NSObject *object  = [notification object];
	if ([object isKindOfClass:[NSDictionary class]]) {
		NSDictionary *dict = (NSDictionary *)object;
		if ([[dict objectForKey:@"Status"] intValue]==1) {
			if ([[dict objectForKey:@"Data"] isKindOfClass:[NSDictionary class]]) {
				NSDictionary *tempDict = (NSDictionary *)[dict objectForKey:@"Data"];
                
				[infoDict setDictionary:tempDict];
                //0921 bug修复
                
                    if (![[infoDict objectForKey:@"EnterpriseName"] isEmptyOrNull]) {
                        companyName.text = [infoDict objectForKey:@"EnterpriseName"];
                        [self setMapPorperites];
                        [listTable reloadData];
                    }
                

				
			}
			else {
				////[self showConnectionError];
			}
		}
		else {
			////[self showConnectionError];
		}
		
	}
	else {
		//[self showConnectionError];
	}			
}

- (void)requestFactorList {
	[self showLoading];
	NSString *body = [NSString stringWithFormat:@"LoginGuid=%@&EnterpriseCode=%@&EnterpriseType=%@",
					  [[AppDelegate_iPad currentDelegate] GUID],code,markEnterpriseTypeCode];
	
	[[CommonJson sharedInstance] requestToPath:[WebPath enterprisePath]
									methodName:@"Search__MonitorSiteMonitorFactor" 
									bodyString:body 
									 targetObj:self
							  targetMethodName:@"eventForFactorList:" 
									notifiName:@"RequestCompanyFactorList"];
}
- (void)eventForFactorList:(NSNotification *)notification {
	[[CommonJson sharedInstance] removeTarget:self notiName:[notification name]];
	[self hideLoading];
	NSObject *object  = [notification object];
	if ([object isKindOfClass:[NSDictionary class]]) {
		NSDictionary *dict = (NSDictionary *)object;
		if ([[dict objectForKey:@"Status"] intValue]==1) {
			if ([[dict objectForKey:@"Data"] isKindOfClass:[NSArray class]]) {
				[factorData setArray:[dict objectForKey:@"Data"]];
				if ([factorData count]) {
					[self setupFactorBts];
				}
			}
			else {
				//[self showConnectionError];
			}
		}
		else {
			//[self showConnectionError];
		}
		
	}
}
#pragma mark 设置排放口
- (void)setupFactorBts {
	for (UIView *view in factorBtHolder.subviews) {
		[view removeFromSuperview];
	}
	float started = 1.0f;
	int selectsiteindex=0;
    if (factorData !=nil && ![factorData isKindOfClass:[NSNull class]]) {
        for (int i=0;i<[factorData count];i++) 
        {
            NSDictionary *dict=(NSDictionary *)[factorData objectAtIndex:i];
            NSString *string = [NSString stringWithFormat:@"%@",[dict objectForKey:@"MonitorSiteName"]];
            NSString *sitecodestring=[NSString stringWithFormat:@"%@",[dict objectForKey:@"MonitorSiteCode"]];
            CGSize size = [string sizeWithFont:[UIFont systemFontOfSize:15.0f]];
            float width = (size.width > 98.0f) ? size.width + 10.0f : 98.0f;
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button addTarget:self action:@selector(factorBtPressed:) forControlEvents:UIControlEventTouchUpInside];
            [button setTitle:string forState:UIControlStateNormal];
            [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:15.0f];
            button.frame = CGRectMake(started, 1.0f, width, 27.0f);
            [button setBackgroundImage:[UIImage imageNamed:@"btn98x27_1.png"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"btn98x27_2.png"] forState:UIControlStateSelected];
            [button setBackgroundImage:[UIImage imageNamed:@"btn98x27_2.png"] forState:UIControlStateHighlighted];
            button.tag = 1000 + i;
            if (![sitecodestring isEmptyOrNull] && [sitecodestring isEqualToString:marksiteCode]) {
                button.selected=YES;
                selectsiteindex=i;
            }
            else
                button.selected=NO;
            [factorBtHolder addSubview:button];
            started += width;
        }
        if ([factorData count]) {
            UIButton *button = (UIButton *)[factorBtHolder viewWithTag:1000+selectsiteindex];
            [button sendActionsForControlEvents:UIControlEventTouchUpInside];
        }
        factorBtHolder.contentSize = CGSizeMake(started,factorBtHolder.bounds.size.height);
    }
    
	
}
//加载因子
- (void)factorBtPressed:(id)sender {
	
	for (int i = 0; i < [factorData count]; i ++) {
		UIButton *button = (UIButton *)[factorBtHolder viewWithTag:1000 + i];
		button.selected = NO;
	}
	
	UIButton *button = (UIButton *)sender;
	button.selected = YES;
	int tag = button.tag - 1000;
	if (factorData !=nil && [factorData count]>tag) {
		NSDictionary *dict = [factorData objectAtIndex:tag];
		[selectedFactorDict setDictionary:dict];//选中排放口数据
		[subFactors setArray:[dict objectForKey:@"MonitorFactorList"]];//因子
		[subFactorTable reloadData];
	}
	
	if (![markfactoryCode isEmptyOrNull]) {
		for (int i=0; i<[subFactors count];i++) {
			NSDictionary *dict = [subFactors objectAtIndex:i];
			NSString *factoryCode=[dict objectForKey:@"PollutionFactorCode"];
			if (![markfactoryCode isEmptyOrNull] && [markfactoryCode isEqualToString:factoryCode]) {
				[subFactorTable selectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]
											animated:YES 
									  scrollPosition:UITableViewScrollPositionTop];
				selectedSubFactorRow=i;
				markfactoryCode=@"";
				break;
			}
		}
	}
	else {
		[subFactorTable selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
									animated:YES 
							  scrollPosition:UITableViewScrollPositionTop];
		selectedSubFactorRow = 0;
	}
	
	[self requestDataForDateTag:leftSeg.selectedSegmentIndex RowTag:selectedSubFactorRow];
}

- (void)requestDataForDateTag:(NSInteger )dateTag RowTag:(NSInteger )rowTag {
	[self showLoading];
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	NSString *start;
	NSString *end;
	
	[dateFormatter setDateFormat:@"yyyy-MM-dd 00:00"];
	start=[dateFormatter stringFromDate:[NSDate date]];
	NSDate *date = [NSDate dateWithTimeIntervalSinceNow:-60*60*24];
	NSString *yesterday = [dateFormatter stringFromDate:date];
	
	[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
	end=[dateFormatter stringFromDate:[NSDate date]];
	
	NSString *siteCode =[selectedFactorDict objectForKey:@"MonitorSiteCode"];
	NSString *siteType = [selectedFactorDict objectForKey:@"MonitorSiteTypeCode"];
	NSString *factorCode=@"";
	if (![subFactors isKindOfClass:[NSNull class]] && [subFactors count]>rowTag) {
		factorCode = [[subFactors objectAtIndex:rowTag] objectForKey:@"PollutionFactorCode"];
	}
	
	NSString *body;
	NSString *method;
	
	NSString *loginGuid=[[AppDelegate_iPad currentDelegate] GUID];
    //修改流量单位
    if (![subFactors isKindOfClass:[NSNull class]] && [subFactors count]>0) {
        for (int i=0;i<[subFactors count];i++) {
            NSDictionary * dir = [subFactors objectAtIndex:i];
            NSString * fac=[NSString stringWithFormat:@"%@",[dir objectForKey:@"PollutionFactorCode"]];
            if ([fac isEqualToString:@"B01"] || [fac isEqualToString:@"B02"]) {
                NSString *unitName=[self unitName:fac btnTag:dateTag];
                UITableViewCell *subfactorycell=[subFactorTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
                subfactorycell.textLabel.text=[NSString stringWithFormat:@"%@ (单位：%@ )",
                                               [dir objectForKey:@"PollutionFactorName"],unitName];            
                break;
            }
        }
    }
    
    switch (dateTag) {
		case 0:
			//实时数据
			body = [NSString stringWithFormat:@"LoginGuid=%@&MonitorSiteCode=%@&MonitorSiteTypeCode=%@&PollutionFactorCode=%@&DateTimeFrom=%@&DateTimeTo=%@"
					,loginGuid,siteCode,siteType,factorCode
					,start,end];
			method = @"Search__EnterpriseData_RealTime";
			break;
		case 1:
			//小时数据
			body = [NSString stringWithFormat:@"LoginGuid=%@&MonitorSiteCode=%@&MonitorSiteTypeCode=%@&PollutionFactorCode=%@&DateTimeFrom=%@&DateTimeTo=%@"
					,loginGuid,siteCode,siteType,factorCode
					,start,end];
			method = @"Search__EnterpriseData_Hour";
			break;
		case 2:
			//昨日数据
			end=start;
			start=yesterday;
			body = [NSString stringWithFormat:@"LoginGuid=%@&MonitorSiteCode=%@&MonitorSiteTypeCode=%@&PollutionFactorCode=%@&DateTimeFrom=%@&DateTimeTo=%@",
					loginGuid,siteCode,siteType,factorCode,start,end];
			method = @"Search__EnterpriseData_Hour";
			break;
		case 3:
			//三十天取的是日数据
			[dateFormatter setDateFormat:@"yyyy-MM-01 00:00"];
			start=[dateFormatter stringFromDate:[NSDate date]];
			[dateFormatter setDateFormat:@"yyyy-MM-dd 23:59"];
			end=[dateFormatter stringFromDate:[NSDate date]];
			body = [NSString stringWithFormat:@"LoginGuid=%@&MonitorSiteCode=%@&MonitorSiteTypeCode=%@&PollutionFactorCode=%@&DateTimeFrom=%@&DateTimeTo=%@",
					loginGuid,siteCode,siteType,factorCode,start,end];
			method = @"Search__EnterpriseData_Day";
			break;
		case 4:

			[dateFormatter setDateFormat:@"yyyy-MM-dd 00:00"];
			start=[dateFormatter stringFromDate:selectDate];
			[dateFormatter setDateFormat:@"yyyy-MM-dd 23:59"];
			end=[dateFormatter stringFromDate:selectDate];
			
			body = [NSString stringWithFormat:@"LoginGuid=%@&MonitorSiteCode=%@&MonitorSiteTypeCode=%@&PollutionFactorCode=%@&DateTimeFrom=%@&DateTimeTo=%@"
					,loginGuid,siteCode,siteType,factorCode
					,start,end];
			//method = @"Search__EnterpriseData_Hour";
			method = @"Search__EnterpriseData_History";
			break;
		default:
			break;
	}
	
	[[CommonJson sharedInstance] requestToPath:[WebPath enterprisePath]
									methodName:method 
									bodyString:body 
									 targetObj:self
							  targetMethodName:@"eventForData:" 
									notifiName:@"RequestCompanyPollutionData"];
	[dateFormatter release]; 
	
}

- (void)eventForData:(NSNotification *)notification {
	[[CommonJson sharedInstance] removeTarget:self notiName:[notification name]];
	NSObject *object  = [notification object];
	if ([object isKindOfClass:[NSDictionary class]])
	{
		NSDictionary *dict = (NSDictionary *)object;
		if ([[dict objectForKey:@"Status"] intValue]) {
			if ([[dict objectForKey:@"Data"] isKindOfClass:[NSArray class]] || [[dict objectForKey:@"Data"] isKindOfClass:[NSDictionary class]]) {
								
				[dataArray setArray:[dict objectForKey:@"Data"]];
				[self reloadChartForArray:dataArray];
				if (rightSeg.selectedSegmentIndex == 1) {
					[listTable reloadData];
				}
			}
			else {
				//[self showConnectionError];
			}
		}
		else {
			//[self showConnectionError];
		}
		
	}
	else {
		//[self showConnectionError];
	}	
	[self hideLoading];
}

#pragma mark ConvertTime method
- (NSString *)timeStringForString:(NSString *)string shortFormat:(BOOL)isShort {
	NSMutableString *timeString=[[NSMutableString alloc]init];
	if (string !=nil && ![string isKindOfClass:[NSNull class]]) {
		timeString = [[NSMutableString alloc] initWithString:string];
	}
	//NSMutableString *timeString = [[NSMutableString alloc] initWithString:string];
	[timeString setString:[timeString stringByReplacingOccurrencesOfString:@"/Date(" withString:@""]];
	[timeString setString:[timeString stringByReplacingOccurrencesOfString:@")/" withString:@""]];
	if ([timeString length]>=3) {
		[timeString setString:[timeString substringToIndex:timeString.length - 3]];
	}
	
	NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeString longLongValue]];
	NSDateFormatter *format = [[NSDateFormatter alloc] init];
	if (leftSeg.selectedSegmentIndex==3) {
		[format setDateFormat:@"M月d日"];
	}
	else if (isShort) {
		[format setDateFormat:@"yyyy-MM-dd"];
	}
	else {
		[format setDateFormat:@"yyyy-MM-dd HH:mm"];
	}
	
	
	NSString *returned = [NSString stringWithFormat:@"%@",[format stringFromDate:date]];
	[format release];
	return returned;
	
}
- (void)setMapPorperites {
	[mapView removeAnnotations:[mapView annotations]];
	if (![infoDict objectForKey:@"EnterpriseLongitude"] || ![infoDict objectForKey:@"EnterpriseLatitude"]) {
		return;
	}
	MKCoordinateRegion theRegin;
	CLLocationCoordinate2D theCenter;
	NSString *latiude=[NSString stringWithFormat:@"%@",[infoDict objectForKey:@"EnterpriseLatitude"]];
	NSString *loniude=[NSString stringWithFormat:@"%@",[infoDict objectForKey:@"EnterpriseLongitude"]];
	if (![latiude isEqualToString:@"<null>"] && ![loniude isEqualToString:@"<null>"]) {
		if (abs([latiude floatValue])<=90 && abs([loniude floatValue])<=180) {
			theCenter.latitude = [[infoDict objectForKey:@"EnterpriseLatitude"] floatValue];
			theCenter.longitude = [[infoDict objectForKey:@"EnterpriseLongitude"] floatValue];
		}
		
		
	}
	
	
	theRegin.center=theCenter;
	
	CLLocationCoordinate2D theCoordinate;
	theCoordinate.latitude =theCenter.latitude ;
	theCoordinate.longitude=theCenter.longitude;
	MapAnnotation * ano = [[MapAnnotation alloc] initWithCoords:theCoordinate name:companyName.text];
	
	[mapView addAnnotation:ano ];
	[ano release];
	MKCoordinateSpan theSpan;
	theSpan.latitudeDelta = 0.1;
	theSpan.longitudeDelta = 0.1;
	theRegin.span = theSpan;
	[mapView setRegion:theRegin];
	[mapView regionThatFits:theRegin];
	mapView.showsUserLocation = NO;
}
- (IBAction)leftSegChanged:(id)sender {
	
	if (leftSeg.selectedSegmentIndex == 4) {
		DatePickerVC_iPad *controller = [[DatePickerVC_iPad alloc] init];
		controller.delegate = self;
		controller.contentSizeForViewInPopover = CGSizeMake(320.0f, 216.0f);
		controller.companyDetail=self;
		UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:controller];
		[controller release];
		self.popControlller= [[UIPopoverController alloc] initWithContentViewController:navi];
		[navi release];
		[popControlller presentPopoverFromRect:CGRectMake(220.0f, 0.0f, 55.0f, 30.0f)
							 inView:leftSeg 
		   permittedArrowDirections:UIPopoverArrowDirectionUp 
						   animated:YES];
		return;
	}
	[self requestDataForDateTag:leftSeg.selectedSegmentIndex RowTag:selectedSubFactorRow];
}
- (IBAction)rightSegChanged:(id)sender {
	[listTable reloadData];
}
- (IBAction)focusBtPressed:(id)sender {
	if ([[FocusDataMethod sharedInstance] companyExisting:code]) {
		[[FocusDataMethod sharedInstance] deleteCompany:code];
		focusImageView.hidden = YES;
		[focusBt setTitle:@"关注企业" forState:UIControlStateNormal];
	}
	else {
		NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:code,@"EnterpriseCode",companyName.text,@"EnterpriseName",markEnterpriseTypeCode,@"EnterpriseTypeCode",nil];
		[[FocusDataMethod sharedInstance] addNewCompany:dict];
		focusImageView.hidden = NO;
		[focusBt setTitle:@"取消关注" forState:UIControlStateNormal];
	}
	[[NSNotificationCenter defaultCenter] postNotificationName:@"FocusCompanyHasBeenChanged" object:nil];

}
- (void)reloadChartForArray:(NSArray *)array {
	if ([array count]) {
		NSMutableArray *tempArray = [[NSMutableArray alloc] init];
		for (NSDictionary *dict in array) {
			SC_PointData *point = [[SC_PointData alloc] init];
			NSString *value= [NSString stringWithFormat:@"%@",[dict objectForKey:@"MonitorValue"]];
			point.yValue = [NSNumber numberWithFloat:[value floatValue]];
			point.xLabel = [self timeStringForString:[dict objectForKey:@"MonitorTime"] shortFormat:NO];
			[tempArray addObject:point];
			[point release];
		}
		[curveController setData:tempArray];
		[curveController setChartTitle:companyName.text];
		[tempArray release];
		
		if (subFactors !=nil && [subFactors count]>0) {
			NSDictionary *dict = [subFactors objectAtIndex:selectedSubFactorRow];
			if (![[dict objectForKey:@"StandardUpperLimit"] isKindOfClass:[NSNull class]]) {
				[curveController setStandardValue:[[dict objectForKey:@"StandardUpperLimit"] floatValue]];
			}
			else {
				[curveController setStandardValue:- 999.0f];
			}
		}
		
	}
	else {
		[curveController setData:[NSArray array]];
	}
	
}

#pragma mark MapButtonAction
- (IBAction)mapbuttonPressed:(id)sender  {
	if ([infoDict count]>0) {
		[detaiVCdelegate mapbuttonPressedInDetailPage:infoDict];
	}
}

#pragma mark VC methods

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[backgroundImageView release];
	[leftSeg release];
	[rightSeg release];
	[focusBt release];
	[companyName release];
	[focusImageView release];
	[mapView release];
	[factorBtHolder release];
	[maskView release];
	[mapButton release];
	
	//[activityView release];
	[markEnterpriseCode release];
	[popControlller release];
    [markEnterpriseTypeCode release];
	[marksitetypeCode release];
	[marksiteCode release];
	[markfactoryCode release];
	[maskButton release];
	//[activeIndicator release];
//	[loadingLabel release];
//	[loadingBackImage release];
    [super dealloc];
}
-(NSString *)unitName:(NSString *)factorycode btnTag:(NSInteger)tag
{
    NSString *unitname=@"浓度";
    
    if (factorycode!=nil && ![factorycode isKindOfClass:[NSNull class]]) 
    {
        if ([factorycode isEqualToString:@"B01"]) {
            switch (tag) {
                case 0:
                    //实时
                    unitname=@"升/秒";
                    break;
                case 4:
                    //历史
                    unitname=@"升/秒";
                    break; 
                default:
                    unitname=@"吨";
                    break;
            }
        }
        else if([factorycode isEqualToString:@"B02"])
        {
            switch (tag) {
                case 0:
                    //实时
                    unitname=@"标立方米／秒";
                    break;
                case 1:
                    unitname=@"标立方米";
                    break;
                case 4:
                    //历史
                    unitname=@"标立方米／秒";
                    break; 
                default:
                    unitname=@"千标立方米";
                    break;
            }
        }
    }
    return  unitname;
}
#pragma mark UITableViewDelegate & DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if (tableView == subFactorTable) {
		return [subFactors count];
	}
	if (rightSeg.selectedSegmentIndex == 1) {
		return [dataArray count];
	}
	return ([infoKeyArray count] - 1) * 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSString *CellIdentifier = @"InfoListCell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
									   reuseIdentifier:CellIdentifier] autorelease];
	}	
	if (tableView == subFactorTable) {
		cell.textLabel.font = [UIFont systemFontOfSize:14.0f];
		NSDictionary *dict = [subFactors objectAtIndex:indexPath.row];
		
		//BOOL isOver=NO;
//		BOOL isTrouble=NO;
//		NSString *stateflag=[dict objectForKey:@"StateFlag"];
//		if ([stateflag isEqualToString:@"1"]) {
//			//超标
//			isOver=YES;
//		}
//		if([stateflag isEqualToString:@"2"])
//		{
//			isTrouble=YES;
//		}
		
		NSString *string = [NSString stringWithFormat:@"%@ (单位：%@  ",[dict objectForKey:@"PollutionFactorName"],
							[dict objectForKey:@"MonitorValueUnit"]];
		if (![[dict objectForKey:@"StandardUpperLimit"] isKindOfClass:[NSNull class]]) {
			string = [string stringByAppendingFormat:@"标准上限：%@ )",[dict objectForKey:@"StandardUpperLimit"]];
		}
		else {
			string = [string stringByAppendingString:@")"];
		}
		       
		//if (isOver) {
//			cell.textLabel.textColor=[UIColor redColor];
//		}
//		else if(isTrouble)
//			cell.textLabel.textColor=[UIColor orangeColor];
//		else 
//			cell.textLabel.textColor=[UIColor blackColor];
		
		

		cell.textLabel.text = string;
		if (indexPath.row % 2 != 0) {
			cell.contentView.backgroundColor = [UIColor colorWithRed:246.0f/255.0f green:246.0f/255.0f blue:246.0f/255.0f alpha:1.0f];
		}
		else {
			cell.contentView.backgroundColor = [UIColor whiteColor];
		}
		return cell;
	}
	if (rightSeg.selectedSegmentIndex == 1) {
		cell.textLabel.font = [UIFont systemFontOfSize:15.0f];
		NSDictionary *dict = [dataArray objectAtIndex:indexPath.row];
		NSString *time = [self timeStringForString:[dict objectForKey:@"MonitorTime"] shortFormat:NO];
		NSString *value = [NSString stringWithFormat:@"%@",[dict objectForKey:@"MonitorValue"]];
		
		if (subFactors !=nil && [subFactors count]>selectedSubFactorRow) {
			NSDictionary *dictupper = [subFactors objectAtIndex:selectedSubFactorRow];
			NSString *uppderValue=[dictupper objectForKey:@"StandardUpperLimit"];
			NSString *unit=[dictupper objectForKey:@"MonitorValueUnit"];
			if (![uppderValue isKindOfClass:[NSNull class]]) {
				if ([value floatValue]>[uppderValue floatValue]) {
					cell.textLabel.textColor=[UIColor redColor];
				}
				else {
					cell.textLabel.textColor=[UIColor blackColor];
				}
				
			}
			
			cell.textLabel.text = [NSString stringWithFormat:@"%@     %@(%@)",time,value,unit];
			cell.contentView.backgroundColor = [UIColor whiteColor];			
		}
		return cell;
		
		
	}
	cell.textLabel.textColor=[UIColor blackColor];
	if (indexPath.row < 4) {
		if (indexPath.row % 2 == 0) {
			NSDictionary *dict = [infoKeyArray objectAtIndex:indexPath.row / 2];
			cell.textLabel.text = [NSString stringWithFormat:@"%@:",[dict objectForKey:@"title"]];
			cell.textLabel.font = [UIFont boldSystemFontOfSize:16.0f];
		}
		else {
			NSDictionary *dict =  [infoKeyArray objectAtIndex:(indexPath.row - 1) / 2];
			NSString *key = [dict objectForKey:@"key"];
			//if (![[infoDict objectForKey:key] isKindOfClass:[NSNull class]]) {
			if ([infoDict objectForKey:key] != nil) {
				cell.textLabel.text = [NSString stringWithFormat:@"%@",[infoDict objectForKey:key]];
			}
			else {
				cell.textLabel.text = @"";
			}
			cell.textLabel.font = [UIFont systemFontOfSize:15.0f];
		}
	}
	else if (indexPath.row == 4) {
		cell.textLabel.text = @"经纬度:";
		cell.textLabel.font = cell.textLabel.font = [UIFont boldSystemFontOfSize:16.0f];
	}
	else if (indexPath.row == 5) {
		NSString *latstr=[NSString stringWithFormat:@"%@",[infoDict objectForKey:@"EnterpriseLatitude"]];
		NSString *lonStr=[NSString stringWithFormat:@"%@",[infoDict objectForKey:@"EnterpriseLongitude"]];
		cell.textLabel.font = 	cell.textLabel.font = [UIFont systemFontOfSize:15.0f];
		if (![latstr isEqualToString:@"<null>"] && ![lonStr isEqualToString:@"<null>"]) {
			cell.textLabel.text = [NSString stringWithFormat:@"%@,%@",[infoDict objectForKey:@"EnterpriseLongitude"],
								   [infoDict objectForKey:@"EnterpriseLatitude"]];
		}
		else {
			cell.textLabel.text = @"";
		}
	}
	else {
		if (indexPath.row == 27) {
			NSString *key = @"EnterpriseBuildDate";
			if (![[infoDict objectForKey:key] isKindOfClass:[NSNull class]]) {
				cell.textLabel.text = [NSString stringWithFormat:@"%@",[self timeStringForString:[infoDict objectForKey:key] shortFormat:YES]];
			}
			else {
				cell.textLabel.text = @"";
			}
			cell.textLabel.font = [UIFont systemFontOfSize:15.0f];
		}
		else if (indexPath.row == 29) {
			NSString *key = @"EnterpriseRunDate";
			//if (![[infoDict objectForKey:key] isKindOfClass:[NSNull class]]) {
			if ([infoDict objectForKey:key] != nil) {
				cell.textLabel.text = [NSString stringWithFormat:@"%@",[self timeStringForString:[infoDict objectForKey:key] shortFormat:YES]];
			}
			else {
				cell.textLabel.text = @"";
			}
			cell.textLabel.font = [UIFont systemFontOfSize:15.0f];
		}
		
		else if (indexPath.row % 2 == 0) {
			NSDictionary *dict = [infoKeyArray objectAtIndex:indexPath.row / 2 + 1];
			cell.textLabel.text = [NSString stringWithFormat:@"%@:",[dict objectForKey:@"title"]];
			cell.textLabel.font = [UIFont boldSystemFontOfSize:16.0f];
			
			if ([dict objectForKey:@"title"] == nil) {
				cell.textLabel.text = @"";
			}
			
		}
		else {
			NSDictionary *dict =  [infoKeyArray objectAtIndex:(indexPath.row - 1) / 2 +  1];
			NSString *key = [dict objectForKey:@"key"];
			//if (![[infoDict objectForKey:key] isKindOfClass:[NSNull class]]) {
			if ([infoDict objectForKey:key] != nil) {
				NSString *str=[NSString stringWithFormat:@"%@",[infoDict objectForKey:key]];
				if ([str isEqualToString:@"<null>"]) {
					cell.textLabel.text = @"";
				}else
					cell.textLabel.text =str;
			}
			else {
				cell.textLabel.text = @"";
			}
			cell.textLabel.font = [UIFont systemFontOfSize:15.0f];
		}		
	}
	
	if (indexPath.row % 2 == 0) {
		cell.contentView.backgroundColor = [UIColor colorWithRed:246.0f/255.0f green:246.0f/255.0f blue:246.0f/255.0f alpha:1.0f];
	}
	else {
		cell.contentView.backgroundColor = [UIColor whiteColor];
	}

	
 	return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if (tableView == subFactorTable) {
		
		//if (selectedSubFactorRow != -1) {
			[tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:selectedSubFactorRow inSection:0] animated:NO];
		//}
		
		[self requestDataForDateTag:leftSeg.selectedSegmentIndex RowTag:indexPath.row];
		
		selectedSubFactorRow = indexPath.row;
		return;
	}
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark MapViewdelegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
	
	if ([annotation isKindOfClass:[MapAnnotation class]]) {
		
		MapAnnotation *mapAnno = (MapAnnotation *)annotation;
		static NSString *AnoViewIdentifier = @"voucherMapAnoView";
		MKAnnotationView *anoView = [[MKAnnotationView alloc] initWithAnnotation:mapAnno
																 reuseIdentifier:AnoViewIdentifier];
		anoView.image = [UIImage imageNamed:@"mapPin.png"];
		//anoView.image = nil;
		anoView.canShowCallout = YES;
		UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
		button.tag = mapAnno.tag;
		//[button addTarget:self action:@selector(mapPinDetailPressed:) forControlEvents:UIControlEventTouchUpInside];
		anoView.rightCalloutAccessoryView = button;
		return anoView;
	}
	return nil;
}

#pragma mark DatePickerVC_iPadDelegate
- (void)SelectedDateInDatePicker:(NSDate *)date {
	selectDate=date;
    [selectDate retain];
	[self requestDataForDateTag:leftSeg.selectedSegmentIndex RowTag:selectedSubFactorRow];
}

#pragma mark FocusListVC_iPadDelegate
- (void)pressedOnFocusedCompany:(NSString *)companyCode companyType:(NSString *)companyTypeCode{
	if (companyCode == nil) {
		if (![self.view.subviews containsObject:maskView]) {
			[self.view addSubview:maskView];
		}
		maskView.hidden = NO;
		return;
	}
	if ([self.view.subviews containsObject:maskView]) {
		maskView.hidden = YES;
		[maskView removeFromSuperview];
	}
	
	[self beginRequestForCompany:companyCode companyTypeCode:companyTypeCode];
}

@end
